import fs from "node:fs";
import { createServer } from 'node:http';
import { log } from "console";
import path from 'node:path'
import url from "url";
import { createGzip } from "zlib";
import { LRUCache } from './cache.js'

const CONTENT_TYPE = {
    '.html': 'text/html;charset=utf8',
    '.js': 'application/javascript;charset=utf8',
    '.css': 'text/css;charset=utf8',
    '.json': 'application/json;charset=utf8',
    '.png': 'image/png',
    '.jpg': 'image/jpg',
    '.gif': 'image/gif',
    '.ico': 'image/x-icon',
    '.svg': 'image/svg+xml;charset=utf8',
    'default': 'text/html;charset=utf8'
}

let getContentType = ext => {
    return CONTENT_TYPE[ext] ?? CONTENT_TYPE['default'];
}

const cache = new LRUCache(100);

const server = createServer((request, response) => {
    let pathname = url.parse(request.url).pathname;
    pathname = pathname === '/' ? '/index.html' : pathname;
    let fullpath = path.join(process.cwd(), pathname);
    let ext = path.extname(pathname).toLowerCase();
    let contentType = getContentType(ext);
    response.setHeader('Content-Encoding', 'gzip');
    response.setHeader('Content-Type', contentType);
    if (cache.has(fullpath)) {
        // 从缓存读取内容
        log('读取缓存', fullpath);
        response.end(cache.get(fullpath));
        return;
    }
    let readStream = fs.createReadStream(fullpath);
    let gzipStream = readStream.pipe(createGzip()); //进行gzip压缩
    let buffers = [];
    gzipStream.on('data', buffer => {
        response.write(buffer);
        buffers.push(buffer);
    });
    gzipStream.on('end', () => {
        response.end();
        let data = Buffer.concat(buffers);
        cache.put(fullpath, data);
    });
    readStream.on('error', err => {
        //log(err);
        response.statusCode = 404;
        response.end('Page not found');
    });
});

process.chdir('H:\\js\\vue3官方文档')
server.listen(80);

